import React, { useState, useEffect, useRef } from 'react';
import './App.css';

// This is the necessary complexity, now properly encapsulated in a hook.
const usePagination = (htmlContent, width, maxHeight) => {
  const [pages, setPages] = useState([]);

  useEffect(() => {
    if (!htmlContent) {
      setPages([]);
      return;
    }

    // Create a ruler element in memory, never attach it to the DOM
    const ruler = document.createElement('div');
    ruler.className = 'preview-stage';
    ruler.style.position = 'absolute';
    ruler.style.left = '-9999px';
    ruler.style.top = '-9999px';
    ruler.style.pointerEvents = 'none';
    ruler.style.opacity = '0';
    ruler.style.width = `${width}px`; // Ensure width is constrained

    // We have to append it to the body to get layout calculations, but it's invisible and immediately removed.
    document.body.appendChild(ruler);

    const sourceDiv = document.createElement('div');
    sourceDiv.innerHTML = htmlContent;
    const allNodes = Array.from(sourceDiv.childNodes);

    if (allNodes.length === 0) {
      setPages([htmlContent]);
      document.body.removeChild(ruler); // Cleanup
      return;
    }

    const generatedPages = [];
    let currentPageNodes = [];

    const commitPage = () => {
      if (currentPageNodes.length > 0) {
        generatedPages.push(currentPageNodes.map(n => n.outerHTML || n.textContent).join(''));
      }
    };

    for (const node of allNodes) {
      // Skip empty text nodes
      if (node.nodeType === Node.TEXT_NODE && !node.textContent.trim()) {
        continue;
      }

      const tempNodes = [...currentPageNodes, node];
      ruler.innerHTML = tempNodes.map(n => n.outerHTML || n.textContent).join('');

      if (ruler.scrollHeight > maxHeight && currentPageNodes.length > 0) {
        commitPage();
        currentPageNodes = [node];
        // After committing, the ruler needs to be reset to just the current node for the next loop's measurement
        ruler.innerHTML = currentPageNodes.map(n => n.outerHTML || n.textContent).join('');
      } else {
        currentPageNodes.push(node);
      }
    }

    commitPage(); // Commit the last page

    setPages(generatedPages);

    // Crucial cleanup: remove the ruler from the DOM
    document.body.removeChild(ruler);

  }, [htmlContent, width, maxHeight]);

  // The ruler div is now created and managed entirely within the hook, never rendered.
  // The ruler div is now created and managed entirely within the hook, never rendered.
  return { pages };
};

const Preview = ({ htmlContent }) => {
  // Define the 3:4 aspect ratio constraints
  const previewWidth = 360;
  const previewHeight = previewWidth * 4 / 3;

  const { pages } = usePagination(htmlContent, previewWidth, previewHeight);

  return (
    <>
      {/* The off-screen ruler has been removed from the render path */}
      <div className="pages-container">
        {pages.length > 0 ? (
          pages.map((pageHtml, index) => (
            <div
              key={index}
              className="preview-stage"
              dangerouslySetInnerHTML={{ __html: pageHtml }}
            />
          ))
        ) : (
          <div className="preview-stage" />
        )}
      </div>
    </>
  );
};

export default Preview;